// 购物车状态
export default {
  namespaced: true,
  state: () => ({
    list: []
  }),
  getters: {
    effectiveList: state => state.list.filter(item => item.isEffective),
    selectedList: (state, getters) => getters.effectiveList.filter(item => item.selected),
    allSelectedPrice: (state, getters) => getters.selectedList.reduce((acc, cur) => (acc += cur.count * cur.nowPrice), 0),
    isAll: (state, getters) => getters.effectiveList.every(item => item.selected)
  },
  mutations: {
    addCart (state, good) {
      const index = state.list.findIndex(item => item.skuId === good.skuId)
      if (index > -1) {
        state.list[index].count += good.count
      } else {
        state.list.unshift(good)
      }
    },
    singleCheck (state, { good, selected }) {
      const currentGood = state.list.find(item => item.skuId === good.skuId)
      currentGood.selected = selected
    },
    allCheck (state, selected) {
      state.list.forEach(item => {
        item.selected = selected
      })
    },
    delGood (state, good) {
      const index = state.list.find(item => item.skuId === good.skuId)
      state.list.splice(index, 1)
    },
    changeCount (state, { good, count }) {
      const currentGood = state.list.find(item => item.skuId === good.skuId)
      currentGood.count = count
    }
  },
  actions: {
    addCartAction ({ commit, rootState }, good) {
      if (rootState.user.profile.token) {
        // 已登录
        return '加入购物车成功'
      } else {
        commit('addCart', good)
        return '加入购物车成功'
      }
    },
    singleCheckAction ({ commit, rootState }, { good, selected }) {
      if (rootState.user.profile.token) {
        // 已登录
      } else {
        commit('singleCheck', { good, selected })
      }
    },
    allCheckAction ({ commit, rootState }, selected) {
      if (rootState.user.profile.token) {
        // 已登录
      } else {
        commit('allCheck', selected)
      }
    },
    delGoodAction ({ commit, rootState }, good) {
      if (rootState.user.profile.token) {
        // 已登录
      } else {
        commit('delGood', good)
      }
    },
    changeCountAction ({ commit, rootState }, { good, count }) {
      if (rootState.user.profile.token) {
        // 已登录
      } else {
        commit('changeCount', { good, count })
      }
    }
  }
}
